package com.darker.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @auther lj
 * @date 2018/5/3 16:39
 * @email lmwtuedu@163.com
 */
public class ProxyUtil {
    static{
        System.out.println("在什么时候被调用");
    }

    /**
     * 得到代理对象
     * @param target
     * @param advice
     * @param handler
     * @return
     */
   public static Object getProxy(Object target, Advice advice, InvocationHandler handler){
        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);

        return proxy;
   }

    /**
     * 得到代理对象
     * @param target
     * @param advice
     * @return
     */
   public static Object getProxy(final Object target, final Advice advice){
        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                advice.beforeMethod(method);
                Object object = method.invoke(target, args);
                advice.afterMethod(method);
                return object;
            }
        });

        return proxy;
   }
}
